﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Security;

using ERPStore.Extensions;
using ERPStore.Web.Extensions;

namespace ERPStore.Web.Services
{
	public class UserPrincipalHandler : DelegatingHandler
	{
		protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
		{
			var requestBase = request.GetRequestBase(); 

			var visitorId = request.GetVisitorId();
			var principal = new ERPStore.Models.UserPrincipal(visitorId ?? Guid.NewGuid().ToString());

			if (requestBase != null)
			{
				var authCookie = requestBase.Cookies[FormsAuthentication.FormsCookieName];
				if (authCookie != null)
				{
					var authenticationService = GlobalConfiguration.Configuration.DependencyResolver.GetService<ERPStore.Services.IAccountService>();
					FormsAuthenticationTicket authTicket = null;
					try
					{
						authTicket = FormsAuthentication.Decrypt(authCookie.Value);
					}
					catch
					{
					}

					if (authTicket != null)
					{
						int userId = 0;
						int.TryParse(authTicket.Name, out userId);
						if (userId > 0)
						{
							var id = new FormsIdentity(authTicket);
							principal = new ERPStore.Models.UserPrincipal(id, visitorId);
							var user = authenticationService.GetUserById(userId);
							if (user != null)
							{
								principal.CurrentUser = user;
							}
							else
							{
								principal = new ERPStore.Models.UserPrincipal(visitorId);
								FormsAuthentication.SignOut();
							}
						}
					}
				}
			}

			Thread.CurrentPrincipal = principal;
			if (System.Web.HttpContext.Current != null)
			{
				System.Web.HttpContext.Current.User = principal;
			}

			return base.SendAsync(request, cancellationToken);
		}
	}
}
